/**
 *  Copyright Matt Silbernagel 2010
 *  
 *	This file is part of MobilePrinting.
 *
 *	MobilePrinting is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  MobilePrinting is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with MobilePrinting.  If not, see <http://www.gnu.org/licenses/>.
 */

package edu.uc.labs.MobilePrinting.GUI;

import static edu.uc.labs.MobilePrinting.Configurator.*;

import java.awt.Image;
import java.awt.Toolkit;

/**
 * The purpose of this class is to start a new thread that 
 * animates the systemtray icon until the it's 'done'. By animate
 * 
 * @author Matt Silbernagel
 *
 */
public class IconAnimator extends Thread {

	private static boolean isDone = false;
	private static boolean isSuccess = false;
	
	/**
	 * Constructor
	 */
	public IconAnimator(){}
	
	/**
	 * Run Method is invoked when the Thread starts
	 */
	public void run(){
		/*
		 * We need to make sure that isDone is set to false
		 * when starting the thread, otherwise the icon won't
		 * change after the first time run
		 */
		IconAnimator.isDone = false;
		LOGGER.debug("The IconAnimator Thread is running...");
		// Create an array of the icons that we want to cycle through
		String[] icons = { 
							ICONS + DELIM + IconArray.get("trayicon_prog0"), 
							ICONS + DELIM + IconArray.get("trayicon_prog1"), 
							ICONS + DELIM + IconArray.get("trayicon_prog2"), 
							ICONS + DELIM + IconArray.get("trayicon_prog3") 
						 };
		
		/*
		 * Cycle through the icons, setting each in the SysTray, until 
		 * another method tells us that we are done
		 */
		while(!isDone){
			for ( int i=0; i<icons.length; i++ ) {
				//LOGGER.debug("Setting the SysTray icon to " + icons[i]);
				Image img = Toolkit.getDefaultToolkit().getImage(icons[i]);
				SysTray.setIcon(img);
				if(isDone){ break; }
				try {
					IconAnimator.sleep(200);
				} catch (InterruptedException e) { 
					e.printStackTrace();
				}
			}
		}
		// Now we are done so set the specified (either error or default) 
		// icon again and return the Thread
		if(isSuccess) { 
			SysTray.setDefaultIcon(); 
		} else {
			SysTray.setErrorIcon();
		}
		return;	
	}
	
	/**
	 * Tells this Thread to set the error or default icon and return
	 * @param isSuccess set to true to display the default icon
	 */
	public void finish(boolean isSuccess) {
		IconAnimator.isSuccess = isSuccess; 
		IconAnimator.isDone    = true;
	}
	
	
}
